package com.rental.common.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
public class MyJwtUtils {
    // 自定义密钥
    private static final String SECRET_KEY = "sgrrhehw6516rg16g5a6ef1w6rgq3egr";
    private static final int expirationMinutes = 60;

    public  String generateToken(String content) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("content", content);
        payload.put("exp", DateUtil.offsetMinute(DateUtil.date(), expirationMinutes).getTime());

        return JWTUtil.createToken(payload, SECRET_KEY.getBytes());
    }
    public  String parseToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }

        try {
            JWT jwt = JWTUtil.parseToken(token);
            if (!jwt.setKey(SECRET_KEY.getBytes()).verify()) {
                return null; // 验证失败
            }

            long exp = Long.parseLong(jwt.getPayload("exp").toString());
            if (exp < System.currentTimeMillis()) {
                return null; // Token已过期
            }

            return jwt.getPayload("content").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 解析失败
        }
    }
}
